package be.kuleuven.cs.mop;


import java.io.File;
import java.io.IOException;

import javax.swing.JFileChooser;
import javax.swing.UIManager;

import org.jdom.JDOMException;

import be.kuleuven.cs.mop.app.System;
import be.kuleuven.cs.mop.app.controllers.Controllers;
import be.kuleuven.cs.mop.app.parser.DataParser;
import be.kuleuven.cs.mop.app.parser.ThemeParser;
import be.kuleuven.cs.mop.domain.exceptions.TaskManagerException;
import be.kuleuven.cs.mop.domain.model.Theme;
import be.kuleuven.cs.mop.domain.model.impl.World;
import be.kuleuven.cs.mop.gui.TaskManagerGUI;
import be.kuleuven.cs.mop.gui.logging.LogList;
import be.kuleuven.cs.mop.gui.logging.LoggingConfig;
import be.kuleuven.cs.mop.gui.util.XMLFileChooser;



/**
 * Launcher class for {@link TaskManagerGUI}
 */
public class Launcher {
	
	public static final void main(final String... args) {
		final LogList log = new LogList();
		LoggingConfig.setup(log);
		
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (final Exception e) {
			e.printStackTrace();
		}
		
		new XMLFileChooser();
		
		//	TODO:	Switch back to user selection after debugging
		try {
			//	TODO
			final File xmlTheme =
				open();
//				new File("data/themes.xml");
			if (xmlTheme == null)
				throw new IllegalArgumentException("Please select a theme file");
			
			//	TODO
			final File xmlData	=
				open();
//				new File("data/data.xml");
			if (xmlData == null)
				throw new IllegalArgumentException("Please select a data file");
			
			final System		system		= new System();
			final Controllers	controllers	= new Controllers(system);
			
			parseData(xmlData, parseTheme(xmlTheme, system.getWorld()), controllers);
			new TaskManagerGUI(controllers, log);
		} catch (final Exception e) {
			e.printStackTrace();
			java.lang.System.out.println("ERROR:  " + e.getMessage());
		}
	}
	
	
	
	
	
	private static final File open() {
		final XMLFileChooser xfc = new XMLFileChooser();
		if (xfc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
			return xfc.getSelectedFile();
		return null;
	}
	
	private static final void parseData(final File xml, final Theme theme,
			final Controllers controllers) throws IOException, JDOMException {
		new DataParser().parse(xml, controllers, theme);
	}
	
	private static final Theme parseTheme(final File xml, final World world)
			throws IOException, JDOMException, TaskManagerException {
		return new ThemeParser().parse(xml, world);
	}
	
}